package com.xuanyue.db.xuan.core.tools;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.xuanyue.db.xuan.core.exception.SQLException;
import com.xuanyue.db.xuan.core.table.IPersistence;

public class AheadLoger {
	private Lock lock = new ReentrantLock();
	private RandomAccessFile logger;
	private String logFile;
	private IPersistence persistence;
	private int count=0;
	private int max = 100000;
	private long lastTime;
	private long timeOut=60000;
	
	
	public AheadLoger(IPersistence persistence,String logFile) {
		this(persistence, logFile, 10000);
	}
	public AheadLoger(IPersistence persistence,String logFile,int max) {
		this.persistence = persistence;
		this.logFile = logFile;
		this.max=max;
		try {
			logger = new RandomAccessFile(logFile,"rws");
		} catch (FileNotFoundException e) {
			throw new SQLException(e);
		}
	}
	
	public void logger(int info,boolean value) throws IOException {
		try {
			lock.lock();
			logger.writeInt(info);
			logger.writeBoolean(value);
			count++;
		} finally {
			lock.unlock();
		}
		
	}
	
	public void chechOrSave() {
		if(count==0) {
			return;
		}
		if(count>max||System.currentTimeMillis()-lastTime>timeOut) {
			try {
				lock.lock();
				if(count>max) {
					//关闭流
					logger.close();
					logger=null;
					//持久化
					persistence.save();
					count=0;
					//logFile
					new File(logFile).delete();
					logger = new RandomAccessFile(logFile,"rws");
				}
			}catch (Exception e) {
				throw new SQLException(e);
			}finally {
				lock.unlock();
			}
		}
	}
}
